﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using RFMobile.Database;

namespace RFMobile
{
    public partial class searchScreen : Form
    {
        Stack<Int32> users;
        Stack<Int32> owners;
        Stack<Int32> machines;

        DataTable searchDt;

        Int32 OperationType = -1;
        Int32 UsersId = -1;
        Int32 OwnersId = -1;
        Int32 MachinesId = -1;

        enum operationEnum
        {
            MANTENCION = 1,
            EMERGENCIA = 2,
            INSTALACION = 3
        };

        private void sortStack(Stack<Int32> stack)
        {
            // Orden de array
            Int32[] aux = stack.ToArray();
            stack.Clear();
            for (Int32 i = 0; i < aux.Length; i++)
            {
                stack.Push(aux[i]);
            }
            aux = null;
        }

        public searchScreen()
        {
            users = new Stack<Int32>();
            owners = new Stack<Int32>();
            machines = new Stack<Int32>();

            InitializeComponent();
            this.ShowDialog();
        }

        private void menuItem4_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void menuItem3_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void searchScreen_Load(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            statusBar1.Text = "Escoja un período para la búsqueda.";
            
            // cargar datos para filtros.
            DatabaseManager dbm = new DatabaseManager();
            dbm.BuildDataSet(new String[] { "users", "owner", "machines" }, "filterSet");

            DataTable dt = dbm.Ds.Tables["users"];
            foreach (DataRow dr in dt.Rows)
            {
                string name = dr["name"].ToString() + " " + dr["lastname1"].ToString() + " " + dr["lastname2"].ToString();
                responsibleComboBox.Items.Add(name);
                users.Push(Convert.ToInt32(dr["comtec_id_user"].ToString()));
            }
            sortStack(users);

            dt = dbm.Ds.Tables["owner"];
            foreach (DataRow dr in dt.Rows)
            {
                ownerComboBox.Items.Add(dr["company_name"].ToString());
                owners.Push(Convert.ToInt32(dr["comtec_id_owner"].ToString()));
            }
            sortStack(owners);

            dt = dbm.Ds.Tables["machines"];
            foreach (DataRow dr in dt.Rows)
            {
                machinesComboBox.Items.Add(dr["cod_mainteiner"].ToString());
                machines.Push(Convert.ToInt32(dr["comtec_id_machine"].ToString()));
            }
            sortStack(machines);

            Cursor.Current = Cursors.Default;
        }

        private void tabControl1_GotFocus(object sender, EventArgs e)
        {
            switch (tabControl1.TabIndex)
            {
                case 0:
                    statusBar1.Text = "Escoja un período para la búsqueda.";
                    break;
                case 1:
                    statusBar1.Text = "Use los filtros, para definir la búsqueda.";
                    break;
                case 2:
                    statusBar1.Text = "Seleccione una operación para más detalle.";
                    break;
            }
        }

        private void fromDateTime_ValueChanged(object sender, EventArgs e)
        {
            if (fromDateTime.Value < toDateTime.Value)
            {
                menuItem1.Enabled = true;
            }
            else
            {
                menuItem1.Enabled = false;
            }
        }

        private void toDateTime_ValueChanged(object sender, EventArgs e)
        {
            if (toDateTime.Value > fromDateTime.Value)
            {
                menuItem1.Enabled = true;
            }
            else
            {
                menuItem1.Enabled = false;
            }
        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            // Search Method.
            // Build Datagrid
            Cursor.Current = Cursors.WaitCursor;
            filterSearch();
            Cursor.Current = Cursors.Default;
        }

        private DataTable newOperationTable()
        {
            DataTable table = new DataTable("operation");
            /*
            table.Columns.Add("comtec_id_operation", typeof(int));
            table.Columns.Add("comtec_id_machine", typeof(int));
            table.Columns.Add("operation_type", typeof(int));
            */
            table.Columns.Add("ID", typeof(int));
            table.Columns.Add("Diagnostico", typeof(string));
            table.Columns.Add("Repuestos", typeof(string));
            /*
            table.Columns.Add("value_parts", typeof(float));
            table.Columns.Add("value_work", typeof(float));
            table.Columns.Add("value_others", typeof(float));
            table.Columns.Add("value_total", typeof(float));
            */
            table.Columns.Add("Notas", typeof(string));
            table.Columns.Add("Inicio", typeof(DateTime));
            table.Columns.Add("Termino", typeof(DateTime));
            table.Columns.Add("Demora", typeof(int));
            return (table);
        }

        private void filterSearch()
        {
            DatabaseManager dbm = new DatabaseManager();
            dbm.BuildDataSet("operation", "searchSet");
            searchDt = dbm.Ds.Tables["operation"];

            String expresion = "operation_date_start >= '" + fromDateTime.Value.ToString("dd-MM-yyyy HH:mm:ss") + "' AND operation_date_end <= '" + toDateTime.Value.ToString("dd-MM-yyyy HH:mm:ss") + "'";
            if (OperationType >= 0)
            {
                expresion += " AND operation_type = " + OperationType.ToString();
            }

            if (UsersId >= 0)
            {
                expresion += " AND comtec_id_user = " + UsersId.ToString();
            }

            if (MachinesId >= 0)
            {
                expresion += " AND comtec_id_machine = " + MachinesId.ToString();
            }

            /*
             * if (OwnersId >= 0)
            {
                expresion += " AND comtec_id_owner = " + OwnersId.ToString();
            }
             * 
             */

            String sortOrder = "operation_date_start DESC";
            
            DataRow[] findedRows = searchDt.Select(expresion, sortOrder);
            if (findedRows.Length != 0)
            {
                searchDt = newOperationTable();

                foreach (DataRow dr in findedRows)
                {
                    DataRow nRow = searchDt.NewRow();
                    nRow["ID"] = dr["comtec_id_operation"];
                    nRow["Diagnostico"] = dr["diagnosis"];
                    nRow["Repuestos"] = dr["changed_parts"];
                    nRow["Notas"] = dr["notes"];
                    nRow["Inicio"] = dr["operation_date_start"];
                    nRow["Termino"] = dr["operation_date_end"];
                    nRow["Demora"] = dr["delay"];

                    searchDt.Rows.Add(nRow.ItemArray);
                }
                resultsDataGrid.DataSource = searchDt;
                tabControl1.SelectedIndex = 2;
            }
            else
            {
                MessageBox.Show("No se han encontrado resultados.", "Atención.");
            }
            dbm.Close();
            findedRows = null;
        }

        private void operationTypeComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            switch (operationTypeComboBox.SelectedItem.ToString())
            {
                case "Emergencia":
                    OperationType = (Int32)operationEnum.EMERGENCIA;
                    break;
                case "Mantención":
                    OperationType = (Int32)operationEnum.MANTENCION;
                    break;
                case "Instalación":
                    OperationType = (Int32)operationEnum.INSTALACION;
                    break;
            }
            filterSearch();
            Cursor.Current = Cursors.Default;
        }

        private void responsibleComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            UsersId = users.ToArray()[responsibleComboBox.SelectedIndex];
            filterSearch();
            Cursor.Current = Cursors.Default;
        }

        private void ownerComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            OwnersId = owners.ToArray()[ownerComboBox.SelectedIndex];
            filterSearch();
            Cursor.Current = Cursors.Default;
        }

        private void machinesComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            MachinesId = machines.ToArray()[machinesComboBox.SelectedIndex];
            filterSearch();
            Cursor.Current = Cursors.Default;
        }

        private void resultsDataGrid_Click(object sender, EventArgs e)
        {
            Int32 id = Convert.ToInt32(resultsDataGrid[resultsDataGrid.CurrentRowIndex, 0].ToString());
            detailOperationScreen detail = new detailOperationScreen(id);
        }
    }
}